package com.teacher.hong.listener;

import javax.servlet.*;
import javax.servlet.annotation.WebListener;

import java.io.UnsupportedEncodingException;

/**
 * 我的监听器
 */
@WebListener
public class MyListener implements ServletContextListener, ServletContextAttributeListener,
        ServletRequestListener, ServletRequestAttributeListener {


    @Override
    public void contextInitialized(ServletContextEvent sce) {
        //在这里写一些项目初始化工作的代码
        ServletContext context = sce.getServletContext();       //通过ServletContext事件对象获取ServletContext源对象
        context.setAttribute("visits", context.getInitParameter("visits")); //将ServletContext初始值中的visits放入ServletContext的属性中

        System.out.println("ServletContext创建好了");
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        //在这里写一些web容器关闭的时候的一些代码，比如一些资源释放等
        System.out.println("ServletContext销毁了");
    }

    @Override
    public void attributeAdded(ServletContextAttributeEvent scae) {
//        System.out.println("ServletContext新增属性了，新增的属性名：" + scae.getName() + "，属性值：" + scae.getValue());
    }

    @Override
    public void attributeRemoved(ServletContextAttributeEvent scae) {
//        System.out.println("ServletContext删除属性了，删除的属性名：" + scae.getName() + "，属性值：" + scae.getValue());
    }

    @Override
    public void attributeReplaced(ServletContextAttributeEvent scae) {
//        System.out.println("ServletContext替换属性了，替换的属性名：" + scae.getName() + "，属性值：" + scae.getValue());
    }

    @Override
    public void attributeAdded(ServletRequestAttributeEvent srae) {
//        System.out.println("ServletRequest新增属性了，新增的属性名：" + srae.getName() + "，属性值：" + srae.getValue());
    }

    @Override
    public void attributeRemoved(ServletRequestAttributeEvent srae) {
//        System.out.println("ServletRequest移除属性了，移除的属性名：" + srae.getName() + "，属性值：" + srae.getValue());
    }

    @Override
    public void attributeReplaced(ServletRequestAttributeEvent srae) {
//        System.out.println("ServletRequest替换属性了，替换的属性名：" + srae.getName() + "，属性值：" + srae.getValue());
    }

    @Override
    public void requestInitialized(ServletRequestEvent sre) {
        //在这里写一些请求初始化的代码
        ServletRequest request = sre.getServletRequest();
        try {
            request.setCharacterEncoding("utf-8");  //设置请求的字符集编码
        } catch (UnsupportedEncodingException exception) {
            exception.printStackTrace();
        }

//        System.out.println("ServletRequest创建好了");
    }

    @Override
    public void requestDestroyed(ServletRequestEvent sre) {
        //在这里写一些请求执行完毕被销毁的代码
//        System.out.println("ServletRequest执行完毕，销毁了");
    }
}
